package com.springboot_blog.config;

import com.springboot_blog.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * JWT认证过滤器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, 
                                    HttpServletResponse response, 
                                    FilterChain filterChain) throws ServletException, IOException {
        
        try {
            // 1. 从请求头中获取JWT token
            String token = getTokenFromRequest(request);
            log.debug("请求路径: {}, 获取到的token: {}", request.getRequestURI(), 
                    token != null ? token.substring(0, Math.min(20, token.length())) + "..." : "null");
            
            if (StringUtils.hasText(token) && jwtUtil.isValidToken(token)) {
                // 2. 解析token获取用户信息
                Claims claims = jwtUtil.getClaimsFromToken(token);
                String username = claims.getSubject();
                Long userId = claims.get("userId", Long.class);
                String roleCode = claims.get("roleCode", String.class);
                
                // 3. 验证token是否在Redis中存在（防止token被注销）
                String tokenKey = "token:" + userId;
                String redisToken = (String) redisTemplate.opsForValue().get(tokenKey);
                
                if (redisToken != null && redisToken.equals(token)) {
                    // 4. 构建Spring Security的认证对象
                    List<SimpleGrantedAuthority> authorities = Collections.singletonList(
                        new SimpleGrantedAuthority(roleCode)
                    );
                    
                    UsernamePasswordAuthenticationToken authentication = 
                        new UsernamePasswordAuthenticationToken(username, null, authorities);
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    
                    // 5. 设置到Security上下文中
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    
                    log.debug("用户 {} 认证成功，角色: {}, 权限: {}", username, roleCode, authorities);
                } else {
                    log.warn("Token在Redis中不存在或已过期，用户: {}", username);
                }
            }
        } catch (Exception e) {
            log.error("JWT认证过程中发生错误: {}", e.getMessage());
            // 清除可能的错误认证信息
            SecurityContextHolder.clearContext();
        }
        
        // 继续过滤器链
        filterChain.doFilter(request, response);
    }

    /**
     * 从请求中提取JWT token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        // 1. 从Authorization头中获取
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        
        // 2. 从请求参数中获取（可选）
        String tokenParam = request.getParameter("token");
        if (StringUtils.hasText(tokenParam)) {
            return tokenParam;
        }
        
        return null;
    }

    /**
     * 对于某些路径，跳过JWT认证
     */
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        String path = request.getRequestURI();
        
        // 跳过认证的路径
        return path.startsWith("/auth/") || 
               path.startsWith("/doc.html") ||
               path.startsWith("/webjars/") ||
               path.startsWith("/swagger-") ||
               path.startsWith("/v3/api-docs") ||
               path.equals("/favicon.ico") ||
               path.equals("/error");
    }
}
